package se.sweco.ws;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;

public class TrafficServlet extends AbstractServlet {
	public static final String DEFAULT_PATH = "/traffic";

	private DataStore storage;
	
	public TrafficServlet(DataStore storage) {
		this.storage = storage;
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/* Set XML content-type */
		response.setContentType("text/xml; charset=UTF-8");

		double lon = 0, lat = 0, radius = 0;
		try {
			lon = Double.parseDouble(request.getParameter("lon"));
			lat = Double.parseDouble(request.getParameter("lat"));
			radius = Double.parseDouble(request.getParameter("r"));
		} catch (Exception ex) {
			writeString(response.getWriter(), INVALID_PARAMS);
			return;
		}

		if (lon < 0 || lat < 0 || radius < 0) {
			writeString(response.getWriter(), INVALID_PARAMS);
			return;
		}

		Document doc = storage.getTrafficData(lon, lat, radius);

		writeDocument(response.getWriter(), doc);
	}
	
	private static final long serialVersionUID = ("urn:" + TrafficServlet.class.getName()).hashCode();
	
}
